<template>
  <form-item-wrapper :designer="designer" :field="field" :rules="rules" :design-state="designState"
                     :parent-widget="parentWidget" :parent-list="parentList" :index-of-parent-list="indexOfParentList"
                     :in-table-flag="inTableFlag" :column-prop="columnProp" :sub-form-row-index="subFormRowIndex"
                     :sub-form-col-index="subFormColIndex" :sub-form-row-id="subFormRowId">

    <el-select-v2 ref="fieldEditor" v-model="fieldModel" v-show="!isReadMode" :key="selectKey"
                  :multiple="field.options.multiple" :options="field.options.optionItems"
                  :value-key="field.options.valueKey"
                  :clearable="field.options.clearable" :disabled="field.options.disabled" :loading="loadingFlag"
                  :placeholder="field.options.placeholder || i18nt('render.hint.selectPlaceholder')"
                  :filterable="field.options.filterable" :remote="field.options.remote" :remote-method="remoteMethod"
                  :automatic-dropdown="true" popper-class="vxe-table--ignore-clear" @keydown.capture="handleKeyDown"
                  @change="handleChangeEvent" @visible-change="handleVisibleChange">
      <template #empty>
        <div v-for="item in field.options.optionItems">
          {{ item.name }}
        </div>
      </template>
    </el-select-v2>
    <template v-if="isReadMode">
      <span class="readonly-mode-field">{{ optionLabel }}</span>
    </template>
  </form-item-wrapper>
</template>

<script>
import FormItemWrapper from './form-item-wrapper'
import emitter from '@/utils/emitter'
import i18n from '@/utils/i18n'
import fieldMixin from '@/components/form-designer/form-widget/field-widget/fieldMixin'
import { generateId } from '@/utils/util'
import serviceMixin from '@/components/form-render/serviceMixin'

export default {
  name: 'select-widget',
  componentName: 'FieldWidget',  //必须固定为FieldWidget，用于接收父级组件的broadcast事件
  mixins: [emitter, fieldMixin, i18n, serviceMixin],
  props: {
    field: Object,
    parentWidget: Object,
    parentList: Array,
    indexOfParentList: Number,
    designer: Object,

    designState: Boolean,

    subFormRowIndex: { /* 子表单组件行索引，从0开始计数 */
      type: Number,
      default: -1,
    },
    subFormColIndex: { /* 子表单组件列索引，从0开始计数 */
      type: Number,
      default: -1,
    },
    subFormRowId: { /* 子表单组件行Id，唯一id且不可变 */
      type: String,
      default: '',
    },
  },
  components: {
    FormItemWrapper,
  },
  data() {
    return {
      oldFieldValue: null, //field组件change之前的值
      fieldModel: null,
      rules: [],
      widgetKey: '',
      searchValue: '', //远程查询时，会将此变量作为参数传入
      remoteSearchFlag: false,
      visibleChange: false,
    }
  },
  watch: {
    fieldModel(val) {
      console.log('watch', val)
    },
  },
  computed: {
    allowDefaultFirstOption() {
      return !!this.field.options.filterable || !!this.field.options.remote
    },

    remoteMethod() {
      if (!!this.field.options.remote) {
        return this.remoteQuery
      } else {
        return undefined
      }
    },

    selectKey() {
      return this.widgetKey || this.field.id
    },

  },
  beforeCreate() {
    /* 这里不能访问方法和属性！！ */
  },

  created() {
    /* 注意：子组件mounted在父组件created之后、父组件mounted之前触发，故子组件mounted需要用到的prop
       需要在父组件created中初始化！！ */
    // console.log('select created', this.designState)
    this.registerToRefList()
    this.initFieldModel()
    console.log('select created', this.field.options.optionItems)
    // this.setValue(20, true)
    //如果是表格内组件，不需要转换选项
    // this.initOptionItems()
    this.initEventHandler()
    this.buildFieldRules()

    this.handleOnCreated()

    //如果是表格内组件，数据已经加载完成，则不需要再加载
    !this.inTableFlag && this.field.options?.autoLoad && this.loadData()
    // this.field.options?.autoLoad && this.loadData()
  },

  mounted() {
    // console.log('select mounted', this.designState)
    this.handleOnMounted()
  },

  beforeUnmount() {
    this.unregisterFromRefList()
  },

  methods: {

    /**
     * 获取选中项label
     * @return {*}
     */
    getSelectedLabel() {
      return this.$refs.fieldEditor.inputRef.value
    },
    refreshWidgetKey() {  //强制刷新组件！！
      this.widgetKey = 'select-key-' + generateId()
    },
    /*getItem() {
      if (isNotEmpty(this.fieldModel)) {
        return this.field.options.optionItems.find(item => item[this.field.options.valueKey] === this.fieldModel)
      }
    },*/
    /**
     * 按回车后才触发远程方法
     * @param event
     */
    handleKeyDown(event) {
      if (event.key === 'Enter') {
        if (this.visibleChange) {
          const $table = this.getDataTableWidget()
          const { row, column } = $table.getEditRecord()
          const columns = $table.getColumns()
          const firstColumn = columns[0]
          const nextColumnIndex = $table.getColumnIndex(column) + 1// 获取列索引
          const nextRowIndex = $table.getRowIndex(row) + 1
          const tableData = $table.getTableData().visibleData
          let nextRow = row
          if (nextColumnIndex < columns.length - 1) {
            setTimeout(() => {
              $table.setSelectCell(row, columns[nextColumnIndex])
            })
          } else if (nextRowIndex >= tableData.length && nextColumnIndex >= columns.length) {
            $table?.clearEdit()
          } else if (nextColumnIndex === columns.length) {
            nextRow = tableData[nextRowIndex]
            setTimeout(() => {
              $table.setSelectCell(nextRow, columns[firstColumn.type == undefined ? 0 : 1])
            })
          }
        }
      }
    },
    handleVisibleChange(visible) {
      this.visibleChange = visible
    },
  },
}
</script>

<style lang="scss" scoped>
/* form-item-wrapper已引入，还需要重复引入吗？ */

.full-width-input {
  width: 100% !important;
}
</style>
